package pl.veneo.wigprofit.model {
	import eu.szemraj.logging.Log;

	import pl.veneo.wigprofit.model.items.IndexData;
	import pl.veneo.wigprofit.model.items.PercentData;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	/**
	 * @author Tomasz Swierszcz, fiodorkrk@gmail.com
	 */
	public class XMLDataParser extends EventDispatcher {
		public static const ON_DATA_PARSED : String = "ON_DATA_PARSED";
		private var  _model : ChartDataModel;

		public function XMLDataParser(model : ChartDataModel) {
			super();
			_model = model;
		}

		public function loadData(url : String) : void {
			var xmlLoader : URLLoader = new URLLoader();
			xmlLoader.addEventListener(Event.COMPLETE, parseXML);
			xmlLoader.addEventListener(ErrorEvent.ERROR, onError);
			xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			var urlRequest : URLRequest = new URLRequest(url);
			xmlLoader.load(urlRequest);
		}

		private function onError(event : ErrorEvent) : void {
			trace("ERROR: " + event.toString());
			Log.error("ERROR: " + event.toString());
		}

		private function parseXML(event : Event) : void {
			var sXML : XML = new XML(event.target['data']);
			var sessionList : XMLList = sXML['session'];

			for each (var session:XML in sessionList) {
				_model.pushIndex(new IndexData(String(session.attribute("date")), Number(session.attribute("index"))));
				_model.pushPercent(new PercentData(String(session.attribute("date")), Number(session.attribute("percent"))));
			}

			dispatchEvent(new Event(ON_DATA_PARSED));
		}
	}
}
